package net.alan.common.utils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 李岩飞
 * @email eliyanfei@126.com
 * 2017年11月20日 下午4:18:55
 */
public abstract class IOUtils {
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

    /**
     * closeQuietly
     *
     * @param closeable 自动关闭
     */
    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }

    /**
     * InputStream to String utf-8
     *
     * @param input the <code>InputStream</code> to read from
     * @return the requested String
     * @throws NullPointerException if the input is null
     * @throws IOException          if an I/O error occurs
     */
    public static String toString(InputStream input) throws IOException {
        return toString(input, Charsets.UTF_8);
    }

    /**
     * InputStream to String
     *
     * @param input   the <code>InputStream</code> to read from
     * @param charset the <code>Charset</code>
     * @return the requested String
     * @throws NullPointerException if the input is null
     * @throws IOException          if an I/O error occurs
     */
    public static String toString(InputStream input, Charset charset) throws IOException {
        InputStreamReader in = new InputStreamReader(input, charset);
        StringBuffer out = new StringBuffer();
        char[] c = new char[DEFAULT_BUFFER_SIZE];
        for (int n; (n = in.read(c)) != -1; ) {
            out.append(new String(c, 0, n));
        }
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(input);
        return out.toString();
    }

    /**
     * InputStream to File
     *
     * @param input the <code>InputStream</code> to read from
     * @param file  the File to write
     * @throws IOException id异常
     */
    public static void toFile(InputStream input, File file) throws IOException {
        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        while ((bytesRead = input.read(buffer, 0, DEFAULT_BUFFER_SIZE)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(input);
    }

    public static List<String> readListFromFile(final File file, final String[] except) throws IOException {
        return readListFromFile(new FileInputStream(file), except);
    }

    public static List<String> readListFromFile(final InputStream stream, final String[] exceptStartwith) throws IOException {
        final List<String> result = new ArrayList<String>();
        final BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(stream));
        String s;
        try {
            while ((s = bufferedreader.readLine()) != null) {
                if (exceptStartwith != null) {
                    boolean contain = false;
                    for (final String except : exceptStartwith) {
                        if (s.startsWith(except)) {
                            contain = true;
                            break;
                        }
                    }
                    if (contain)
                        continue;
                }
                result.add(s);
            }
        } catch (Exception e) {
        } finally {
            closeIO(stream);
        }

        return result;
    }

    /**
     * 安装关闭多个输入或者输出的流或者任何IO资源
     *
     * @param ioObjects
     */
    public static final void closeIO(final Closeable... ioObjects) {
        if (null == ioObjects || ioObjects.length == 0)//
            return;
        for (final Closeable ioObject : ioObjects) {
            try {
                if (null != ioObject)
                    ioObject.close();
            } catch (final Throwable e) {// ignore
            }
        }
    }

    public static void copyStream(final InputStream is, String file) {
        OutputStream os = null;
        try {
            new File(file).getParentFile().mkdirs();
            os = new FileOutputStream(file);
            copyStream(is, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeIO(is);
            closeIO(os);
        }
    }


    /**
     * 将从输入流中读取数据并写入到输出流
     *
     * @return 整个过程拷贝的字节数据数
     */
    public static void copyStream(final InputStream in, final OutputStream out) throws IOException {
        int readedCount = 0;
        final byte[] tmpBuf = new byte[1024];// 10K
        while (true) {
            final int numRead = in.read(tmpBuf);
            if (numRead == -1)
                break;
            out.write(tmpBuf, 0, numRead);
            out.flush();
            readedCount += numRead;
        }
    }

    /**
     * 将从输入流中读取数据并写入到输出流
     *
     * @return 整个过程拷贝的字节数据数
     */
    public static void copyStream(final File file, final OutputStream out) throws IOException {
        InputStream fis = null;
        try {
            fis = new FileInputStream(file);
            copyStream(fis, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeIO(fis);
        }
    }

    /**
     * 获取文件后缀
     */
    public static String getPostFix(String path) {
        return getPostFix(new File(path));
    }
    public static String getPostFix(File f) {
        String fileName = f.getName();
        String postfix = f.getName().substring(f.getName().lastIndexOf(".") + 1, f.getName().length());
        return postfix;
    }
}
